package com.orange.powerdownload.learn;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description: 直接提交队列
 */
public class PoolTest03 {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPool = null;
        try {
            //创建线程池对象
            threadPool = new ThreadPoolExecutor(
                    2
                    , 3
                    , 1
                    , TimeUnit.MINUTES
                    , new SynchronousQueue<>()
            );

            //创建任务
            Runnable r = () -> {
                System.out.println(Thread.currentThread().getName());
            };

            //将任务提交给线程池
            for (int i = 0; i < 3; i++) {
                threadPool.execute(r);
            }

            System.out.println(threadPool);

        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭线程池
            if (threadPool != null) {
                //threadPool.shutdown();//温和
                //threadPool.shutdownNow();//暴力
                try {
                    threadPool.shutdown();
                    //等待一分钟，如果线程池没有关闭则会执行起来
                    if (!threadPool.awaitTermination(1, TimeUnit.MINUTES)) {
                        threadPool.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    threadPool.shutdownNow();
                }
            }
        }
    }
}
